package com.gitee.andy.rpc.core;

import com.gitee.andy.util.ProtostuffUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class MessageDecoder extends LengthFieldBasedFrameDecoder {

	private final Class<?> clazz;

	public MessageDecoder(Class<?> clazz) {
		super(Integer.MAX_VALUE, 0, 4, 0, 4);
		this.clazz = clazz;
	}

	@Override
	protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
		ByteBuf frame = (ByteBuf) super.decode(ctx, in);
		byte[] dst = new byte[frame.readableBytes()];
		frame.readBytes(dst);
		return ProtostuffUtil.deserialize(clazz, dst);
	}

}
